package com.platform.cdcs.fragment.operation;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.platform.cdcs.R;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.ViewTool;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * Created by holytang on 2017/10/6.
 */
public class PackageEditFragment extends BaseFragment {

    private String[] typeArray, unitArray;
    private JSONArray jsonArray;
    private EditText typeET, numET, unitET;
    private String mclass;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mclass = getArguments().getString("class");
        }
    }

    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        setTitle("套装打包");

        LayoutInflater inflater = LayoutInflater.from(getContext());
        LinearLayout rootView1 = (LinearLayout) view.findViewById(R.id.button1);
        typeET = ViewTool.createEditItem(inflater, "套包型号", rootView1, false, true);
        typeET.setHint("请选择套包型号");
        typeET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showType();
            }
        });

        numET = ViewTool.createEditItem(inflater, "套包数量", rootView1, false, false);
        numET.setHint("请填写套包数量");
        numET.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        unitET = ViewTool.createEditItemNoLine(inflater, "套包单位", rootView1, false, true);
        unitET.setHint("请选择套包单位");
        unitET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(typeET.getText().toString())){
                    Utils.showToast(getContext(),"请先选择套包型号!");
                    return;
                }
                showUnit();
            }
        });
        view.findViewById(R.id.button2).setVisibility(View.GONE);
        view.findViewById(R.id.button3).setVisibility(View.GONE);
        view.findViewById(R.id.button4).setVisibility(View.GONE);
        view.findViewById(R.id.button5).setVisibility(View.GONE);
        TextView btn = (TextView) view.findViewById(R.id.text);
        btn.setText("完成");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finishClick();
            }
        });
    }

    private void finishClick() {
        if(TextUtils.isEmpty(typeET.getText().toString())){
            Utils.showToast(getContext(),"套包型号不能为空!");
            return;
        }
        if(TextUtils.isEmpty(numET.getText().toString().trim())){
            Utils.showToast(getContext(),"套包数量不能为空!");
            return;
        }
        if(TextUtils.isEmpty(unitET.getText().toString().trim())){
            Utils.showToast(getContext(),"套包单位不能为空!");
            return;
        }
        RefershEvent event=new RefershEvent();
        try {
            event.mclass=Class.forName(mclass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        event.oclass=this.getClass();
        event.bundle=new Bundle();
        event.bundle.putString("name",typeET.getText().toString());
        event.bundle.putString("qty",numET.getText().toString().trim());
        if(!TextUtils.isEmpty(unitET.getText().toString())){
            event.bundle.putString("unit",unitET.getText().toString().substring(0,unitET.getText().toString().lastIndexOf(" ")));
        }else{
            event.bundle.putString("unit","");
        }
        EventBus.getDefault().post(event);
        getActivity().finish();
    }

    @Override
    public int layoutId() {
        return R.layout.five_layout;
    }


    private void showType() {
        if (typeArray == null) {
            requestType();
        } else {
            new TwDialogBuilder(getContext()).setItems("选择套包型号", typeArray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    typeET.setText(typeArray[i]);
                }
            }).create().show();
        }
    }

    private void requestType() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "2");
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        jsonArray = obj.getJSONArray("suteList");
                        typeArray = new String[jsonArray.length()];
                        for (int j = 0; j < jsonArray.length(); j++) {
                            typeArray[j] = jsonArray.getJSONObject(j).getString("suteType");
                        }
                        showType();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                }
            }
        });
    }

    private void requestUnit() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "3");
        map.put("itemCode", typeET.getText().toString());
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        JSONArray jsonArray = obj.getJSONArray("uomList");
                        unitArray = new String[jsonArray.length()];
                        for (int j = 0; j < jsonArray.length(); j++) {
                            if (!TextUtils.isEmpty(jsonArray.getJSONObject(j).getString("uomName"))) {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " (" + jsonArray.getJSONObject(j).getString("uomName") + ")";
                            } else {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " ";
                            }
                        }
                        showUnit();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                    unitArray = null;
                }
            }
        });
    }

    private void showUnit() {
        if (unitArray == null) {
            requestUnit();
        } else {
            new TwDialogBuilder(getContext()).setItems("选择单位", unitArray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    unitET.setText(unitArray[i]);
                }
            }).create().show();
        }
    }
}
